#include"socket.h"
#include"string.h"

struct conf_info
{
	char ips[32];
	short port;
	short lismax;
};


#define  IPS      "ips="
#define  PORT     "port="
#define  LISMAX   "lismax="


int read_conf(struct conf_info *dt)
{
	if(dt==NULL) return -1;

	FILE* fp=fopen("my.conf","r");
	if(NULL==fp) return -1;

	int index=0;
	while(1)
	{
		char buff[128]={0};
		if(NULL==fgets(buff,127,fp)) break;

		++index;
		if(strncmp(buff,"#",1)==0 || strncmp(buff,"\n",1)==0)
		{
			continue;
		}

		buff[strlen(buff)-1]=0;//去掉\n

		if(strncmp(buff,IPS,strlen(IPS))==0)
		{
			strcpy(dt->ips,buff+strlen(IPS));
		}
		else if(strncmp(buff,PORT,strlen(PORT))==0)
		{
			dt->port=atoi(buff+strlen(PORT));
		}
		else if(strncmp(buff,LISMAX,strlen(LISMAX))==0)
		{
			dt->lismax=atoi(buff+strlen(LISMAX));
		}
		else
		{
			printf("第%d行，内容无法解析:%s\n",index,buff);
		}
	}
	fclose(fp);

	return 0;
}

int socket_init()
{
	struct conf_info dt;
	if(-1==read_conf(&dt))	return -1;

	//printf("ips:%s\n",dt.ips);
	//printf("port:%d\n",dt.port);
	//printf("lismax:%d\n",dt.lismax);

	int sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(-1==sockfd) return -1;

	struct sockaddr_in saddr;
	memset(&saddr,0,sizeof(saddr));
	saddr.sin_family=AF_INET;
	saddr.sin_port=htons(dt.port);
	saddr.sin_addr.s_addr=inet_addr(dt.ips);

	int res=bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
	if(-1==res) return -1;

	res=listen(sockfd,dt.lismax);

	if(-1==res) return -1;
	return sockfd;



}
